package com.jfinal_demo.app.system;

import com.alibaba.druid.filter.config.ConfigTools;
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.util.JdbcUtils;
import com.alibaba.druid.wall.WallFilter;
import com.jfinal.config.*;
import com.jfinal.json.MixedJsonFactory;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.template.Engine;
import com.jfinal_demo.app.authenticate.AuthenticateInterceptor;
import com.jfinal_demo.app.controllers.ArticalController;
import com.jfinal_demo.app.controllers.TagController;
import com.jfinal_demo.app.controllers.UserController;
import com.jfinal_demo.app.exceptions.ExceptionInterceptor;
import com.jfinal_demo.app.model._MappingKit;

public class MyConfig extends JFinalConfig {
    public void configConstant(Constants constants) {
        loadPropertyFile("databaseConfig.properties");
        constants.setDevMode(getPropertyToBoolean("devMode", true));
        constants.setJsonFactory(new MixedJsonFactory());
        constants.setMaxPostSize(1024 * 1024 * 1024);
        constants.setEncoding("UTF-8");
    }

    public void configRoute(Routes routes) {
        routes.add("/user", UserController.class);
        routes.add("/tag", TagController.class);
        routes.add("/artical", ArticalController.class);
    }

    public void configEngine(Engine engine) {

    }

    public void configPlugin(Plugins plugins) {
        String driver = getProperty("jdbcDriverClass"), url = getProperty("jdbcUrl");
        String user = getProperty("user"), password = getProperty("password");
        boolean isDecrypt = getPropertyToBoolean("decrypt", false);
        try {
            password = isDecrypt ? ConfigTools.decrypt(password) : password;
        } catch (Exception e) {
            e.printStackTrace();
        }
        DruidPlugin dp = new DruidPlugin(url, user, password);
        dp.setDriverClass(driver);
        dp.addFilter(new StatFilter());
        WallFilter wallFilter = new WallFilter();
        wallFilter.setDbType(JdbcUtils.MYSQL);
        wallFilter.setLogViolation(true);

        ActiveRecordPlugin arp = new ActiveRecordPlugin(dp);
        arp.setDialect(new MysqlDialect());
        arp.setBaseSqlTemplatePath(PathKit.getRootClassPath() + "/sqls");
        _MappingKit.mapping(arp);
        arp.addSqlTemplate("all.sql");

        plugins.add(dp);
        plugins.add(arp);
    }

    public void configInterceptor(Interceptors interceptors) {
        interceptors.addGlobalActionInterceptor(new ExceptionInterceptor());
        interceptors.addGlobalActionInterceptor(new AuthenticateInterceptor());
    }

    public void configHandler(Handlers handlers) {

    }
}
